package com.huawei.classroom.student.h14;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Set;
import java.util.HashSet;
import java.io.File;
import java.nio.file.*;
/**
 * 在本包下增加合适的类和方法， 本程序不但要测试通过，还需要写适当的注释
 * 
 * 不要引用jdk1.8以外第三方的包
 * 
 * @author cjy
 *
 */
public class MyTools {

	/**
	 * 
	 * @param studentListFile  存放学生名单的文件名
	 * @param picDir 图片存放的目录（不会包含子目录）
	 */
	public MyTools( ) {
		// TODO Auto-generated constructor stub
	}
	
	private String readFromTxt(String filename) throws Exception {
		Reader reader = null;
		try {
			StringBuffer buf = new StringBuffer();
			char[] chars = new char[1024];
			// InputStream in=new FileInputStream(filename);

			reader = new InputStreamReader(new FileInputStream(filename), "UTF-8");
			int readed = reader.read(chars);
			while (readed != -1) {
				buf.append(chars, 0, readed);
				readed = reader.read(chars);
			}
			return buf.toString();
		} finally {
			close(reader);
		}
	}
	
	private void close(Closeable inout) {
		if (inout != null) {
			try {
				inout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public Set<String> copyToTargetDirAndReturnNoExist(String studentListFile,String srcDir,String target) throws Exception {
		Set<String> set = new HashSet<String>();
		String all = readFromTxt(studentListFile);//第一次分割字符串
		
		File targets = new File(target);
		targets.mkdir();//建立target文件夹
		
		String[] big = all.split("\n");//每一行分割
		for(int i=0; i<big.length; i++) {
			String[] small = big[i].split("\t");//分姓名那些
			String temp=srcDir + small[0] + ".jpg";//找照片
			File check_jpg = new File(temp);
			if(check_jpg.exists() == false) {
				set.add(small[0]);//没上交就被记名
			}
			else {
				//System.out.println(small[2].charAt(0) +  " " + small[2].charAt(1));
				String a_class = "" + small[2].charAt(0);//这是真的恶心，最后还有一个\r，debug到怀疑人生
				File class_name = new File(targets, a_class);

				if(class_name.exists() == false) {
					class_name.mkdir();//班级号的文件夹
				}
				//path1和path2是为了复制jpg文件
				File path1 = new File(temp);
				String temp2 = small[0]+"_"+small[1]+".jpg";
				File path2 = new File(class_name, temp2);
				//System.out.println(temp2);
				//path2.createNewFile();
				try {
					Files.copy(path1.toPath(), path2.toPath());//复制，只能跑一次test，如果path2的文件存在了就会报异常，所以run得先删图片555
				}catch(IOException e) {
					 e.printStackTrace();
				}
				
			}
		}
		return set;
	}
 

}
